﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace WPFTestDemo
{
    /// <summary>
    /// 单元格边框线条。
    /// 为什么要使用自定义的线条类型呢？原因是System.Windows.Shapes.Line绘制的内容在表格容器外会被裁剪，然而我们需要绘制的表格边框
    /// 的半个线条是在表格容器外面的。
    /// </summary>
    public class BorderLine : FrameworkElement
    {
        /// <summary>
        /// 线条界限。
        /// </summary>
        public Rect Bounds => new Rect(StartPoint, EndPoint);

        /// <summary>
        /// 线条颜色画刷。
        /// </summary>
        public Brush Stroke { get; set; }

        /// <summary>
        /// 线条厚度。
        /// </summary>
        public double StrokeThickness { get; set; }

        /// <summary>
        /// 线条起始坐标点(x1,y1)。
        /// </summary>
        public Point StartPoint
        {
            get { return (Point)GetValue(StartPointProperty); }
            set { SetValue(StartPointProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StartPoint.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StartPointProperty =
            DependencyProperty.Register(
                "StartPoint",
                typeof(Point),
                typeof(BorderLine),
                new FrameworkPropertyMetadata(default(Point), FrameworkPropertyMetadataOptions.AffectsRender));


        /// <summary>
        /// 线条结束坐标点(x2,y2)。
        /// </summary>
        public Point EndPoint
        {
            get { return (Point)GetValue(EndPointProperty); }
            set { SetValue(EndPointProperty, value); }
        }

        // Using a DependencyProperty as the backing store for EndPoint.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty EndPointProperty =
            DependencyProperty.Register(
                "EndPoint",
                typeof(Point),
                typeof(BorderLine),
                new FrameworkPropertyMetadata(default(Point), FrameworkPropertyMetadataOptions.AffectsRender));

        /// <inheritdoc/>
        protected override void OnRender(DrawingContext drawingContext)
        {
            drawingContext.DrawLine(new Pen() { Brush = Stroke, Thickness = StrokeThickness }, StartPoint, EndPoint);
        }

        protected override Size MeasureOverride(Size availableSize)
        {
            return Bounds.Size;
        }

        /// <summary>
        /// 初始化实例。
        /// </summary>
        public BorderLine()
        {
            // 不能命中。
            base.IsHitTestVisible = false;
            // 不能获取焦点。
            base.Focusable = false;
            // 咬合到像素。
            base.SnapsToDevicePixels = true;
        }
    }
}
